import advListV from "../view/advList.ejs"
import advTableV from "../components/advTable.ejs";
import {getAdvList, postAdv, putAdvList} from "../api/adv";
const advTypeEnum = {
	1:"轮播图广告",
	2:"轮播图底部广告",
	3:"热门回收广告",
	4:"优品精选广告"
}
let advList = [];
let preImg;
let advInfo = {};
const getAdvListAsync = async function(pageNo=1){
	const response = await getAdvList(pageNo,2,document.querySelector("#keyword").value);
	advList = response.advList;
	document.querySelector("#advTable").innerHTML = advTableV({
		...response,
		advTypeEnum
	});
	document.querySelector("#pageUl").onclick = function(e){
		const pageNo = e.target.dataset.page;
		if(pageNo){
			getAdvListAsync(pageNo/1)
		}
	}
}

export default ()=>{
	return  (req,res)=>{
		res.render(advListV());
		getAdvListAsync();
		preImg = document.querySelector("#preImg");
		// document.querySelector(".input-group-append").onclick = ()=>getAdvListAsync()
		document.querySelector(".input-group-append").onclick =getAdvListAsync.bind(this,1);
		document.querySelector("#addAdvBtn").onclick = function(){
			$("#modal-default").modal("show");
			document.querySelector(".modal-title").innerHTML = "添加广告";
			document.advForm.reset();
			preImg.style.display = "none";
		}
		// 修改按钮
		document.querySelector("#advTable").onclick = async function(e){
			if(e.target.classList.contains("btn-success")){
				// 1- 弹出modal
				$("#modal-default").modal("show");
				// 2- 给表单设置初始值
				document.querySelector(".modal-title").innerHTML = "修改广告"
				advInfo = advList.find(v=>v._id === e.target.dataset.id);
				document.advForm.advTitle.value = advInfo.advTitle;
				document.advForm.advHref.value = advInfo.advHref;
				document.advForm.advOrder.value = advInfo.advOrder;
				document.advForm.advType.value = advInfo.advType;
				preImg.src = "/api/"+advInfo.advPic;
				preImg.style.display = "block";
			}else if(e.target.classList.contains("btn-danger")){
				console.log("删除")
			}
		}
		document.querySelector("#adv-save").onclick = async function(){
			// 收集表单数据
			const form  = new FormData(document.advForm);
			let data;
			if(document.querySelector(".modal-title").innerText==="添加广告"){
				// 发送ajax请求
				data = await postAdv(form);
			}else{
				data = await putAdvList(advInfo._id,form);
			}
			getAdvListAsync();
			toastr.success(data.msg);
			// 清空表单
			document.advForm.reset();
			// 关闭弹出层
			$("#modal-default").modal("hide");
			// 将预览图片
			document.querySelector("#preImg").style.display = "none";

		}
		document.querySelector("#advPic").onchange = function(e){
			const fileReader = new FileReader();
			fileReader.readAsDataURL(e.target.files[0]);
			fileReader.onload = function(e){
				// console.log(11111,e.currentTarget.result);
				preImg.src = e.currentTarget.result;
				preImg.style.display = "block";

			}
		}
	}
}